package Hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class N皇后 {

    List<List<String>> res = new ArrayList<>();
    int n;
    int[] board;
    boolean[] cols;
    boolean[] diag1;
    boolean[] diag2;

    public List<List<String>> solveNQueens(int n) {
        this.n = n;
        board = new int[n];
        cols = new boolean[n];
        diag1 = new boolean[2 * n - 1];
        diag2 = new boolean[2 * n - 1];
        backTracking(0);
        return res;
    }

    private void backTracking(int row) {
        if (row == n) {
            List<String> solution = new ArrayList<>();
            for (int i : board) {
                char[] str = new char[n];
                Arrays.fill(str, '.');
                str[i] = 'Q';
                solution.add(new String(str));
            }
            res.add(solution);
            return;
        }
        for (int col = 0; col < n; col++) {
            if (cols[col] || diag1[row + col] || diag2[row - col + n - 1]) continue;
            board[row] = col;
            cols[col] = true;
            diag1[row + col] = true;
            diag2[row - col + n - 1] = true;
            backTracking(row + 1);
            cols[col] = false;
            diag1[row + col] = false;
            diag2[row - col + n - 1] = false;
        }
    }
}
